﻿using SurfaceAd.Common;
using SurfaceAd.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Sensors;

/**
 * 创建时间：2014/9/19 11:02:01
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace SurfaceAd.Assistant
{
    internal sealed class AuthHelper
    {
        public delegate void LoginHandler(AuthResponse response);
        public event LoginHandler OnLoginHandler;

        public AuthResponse authResponse { get; private set; }
        //

        public AuthHelper()
        {
            this.authResponse = new AuthResponse();
        }

        public void Login(string adRequestUrl, string userId, string adId, string deviceId, string deviceCustomerUserAgent, AdRequestModel adModeType)
        {
            if (NetworkHelper.IsConnectedToInternet())
            {
                //
                string urlQuery = BuildAuthRequestUrl(adRequestUrl, userId, adId, deviceId, deviceCustomerUserAgent, adModeType);
                LogHelper.LogInfo("urlQuery\t" + urlQuery, typeof(AuthHelper));
                urlQuery = Uri.EscapeUriString(ApiHelper.EncodeBase64(Encoding.UTF8, urlQuery));
                if (!string.IsNullOrWhiteSpace(urlQuery))
                {
                    //                    
                    string requestUrl = adRequestUrl + Constants.Ad_REQUESTQUERYKEY + urlQuery;
                    LogHelper.LogInfo("requestUrl\t" + requestUrl, typeof(AuthHelper), "Login");
                    //
                    LoginRequest(requestUrl);
                }
                else
                {
                    LoadOnLoginHandler();
                }
            }
            else
            {
                LoadOnLoginHandler();
                LogHelper.LogError("未连接网络", typeof(AuthHelper), "Login");
            }
        }


        private void LoginRequest(string requestUrl)
        {
            HttpWebRequest request = null;
            try
            {
                request = HttpWebRequest.CreateHttp(new Uri(requestUrl));
                request.Method = "GET";
                request.BeginGetResponse(ResponseCallback, request);
            }
            catch (Exception err)
            {
                if (request != null)
                {
                    request.Abort();
                }
                LogHelper.LogInfo(err.Message, typeof(AuthHelper));
                LoadOnLoginHandler();
            }
            finally
            {
                //异步的，不能终止
            }
        }


        private void ResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            StreamReader streamRead = null;
            string content = string.Empty;
            try
            {
                request = (HttpWebRequest)asynchronousResult.AsyncState;
                response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                //获取应答码
                int statusCode = Convert.ToInt32(response.StatusCode);
                string statusText = response.StatusDescription;

                //应答头信息验证
                using (Stream streamResponse = response.GetResponseStream())
                {
                    //获取请求信息
                    streamRead = new StreamReader(streamResponse, Encoding.UTF8);
                    if (streamRead != null)
                    {
                        content = streamRead.ReadToEnd();
                        if (!string.IsNullOrWhiteSpace(content))
                        {
                            LogHelper.LogInfo("ResponseCallback is result:" + content, typeof(AuthHelper), "ResponseCallback");
                            string baseResult = ApiHelper.DecodeBase64(content);
                            if (!string.IsNullOrWhiteSpace(baseResult))
                            {
                                LogHelper.LogInfo("ResponseCallback is baseResult:" + baseResult, typeof(AuthHelper), "ResponseCallback");
                                this.authResponse = JSONHelper.Deserialize<AuthResponse>(baseResult);
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError("ResponseCallback has error:" + err.Message, typeof(AuthHelper), "ResponseCallback");
                LoadOnLoginHandler();
            }
            finally
            {
                this.LoadOnLoginHandler();
                //
                if (streamRead != null)
                {
                    streamRead.Dispose();
                }
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }

        private void LoadOnLoginHandler()
        {
            if (this.OnLoginHandler != null)
            {
                this.OnLoginHandler(this.authResponse);
            }
        }


        private string BuildAuthRequestUrl(string requestUrl, string adToken, string adPosition, string deviceId, string deviceCustomerUserAgent, AdRequestModel adModeType)
        {
            //no=OVQzVmEFNl85WDNRYRM2XzlK&u=126044002200027149074028009024183101171046007141089100124238&ua=(Win32NT;N;Microsoft Windows NT 8.10.12358.0;zh-CN;Microsoft;XDeviceEmulator)
            //&ver=wp8_1.0.3&net=1&d=0&aid={7927d19e-d12b-4125-ab9c-c843baefb006}&atitle=SurfaceAdSample&aver=1.0.0.0
            //&adesc=SurfaceAdSample author&author=Sample description&apub=SurfaceAdSample&apid={090d2f3c-ffe5-4cf5-9e6e-02cec0987d61}
            StringBuilder requestQuery = new StringBuilder();
            requestQuery.Append("no=").Append(adToken);
            requestQuery.Append("&u=").Append(deviceId);
            requestQuery.Append("&ua=").Append(deviceCustomerUserAgent);
            requestQuery.Append("&ver=").Append(Constants.AdSDKVersion);
            //同步调用方法
            requestQuery.Append("&net=").Append(NetworkHelper.NetInfo.NetAdapterType.Id);
            requestQuery.Append("&d=").Append(Convert.ToInt32(adModeType));
            //应用参数               
            requestQuery.Append("&aid=").Append(AppxManifestHelper.IdentityName);
            requestQuery.Append("&atitle=").Append(AppxManifestHelper.ApplicationsDisplayName);
            requestQuery.Append("&aver=").Append(AppxManifestHelper.IdentityVersion);
            requestQuery.Append("&adesc=").Append(AppxManifestHelper.ApplicationsDescription);
            requestQuery.Append("&author=").Append(AppxManifestHelper.PropertiesPublisherDisplayName);
            requestQuery.Append("&apub=").Append(AppxManifestHelper.IdentityPublisher);//SurfaceAdSample;
            requestQuery.Append("&apid=").Append(AppxManifestHelper.PhoneIdentityPhonePublisherId);// "{090d2f3c-ffe5-4cf5-9e6e-02cec0987d61}");

            return requestQuery.ToString();
        }
    }
}
